/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.financeiro.relatorio;

import br.jm.financeiro.entity.Assunto;
import br.jm.financeiro.entity.Cliente;
import br.jm.financeiro.entity.Usuario;
import br.jm.financeiro.filter.Conecta;
import br.jm.financeiro.filter.Funcoes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer;
import net.sf.jasperreports.engine.fill.JRGzipVirtualizer;

/**
 *
 * @author joao
 */
public class relatorio extends HttpServlet {

//    private RelatorioCertificadoTemp[] selectedCertificadoCheck;
//    private RelatorioCertificadoTemp selectedCertificadoTemp;
//    private TipoTransferencia selectedTipoTransferencia;
//    private Cautela selectedCautela;
    private final Funcoes funcoes = new Funcoes();
    public HttpSession session;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        ServletContext context = getServletContext();
        session = request.getSession(false);
        String cWhere = (String) session.getAttribute("filtroRelatorio");
        String cOrder = (String) session.getAttribute("filtroOrder");
        String cStatus = (String) session.getAttribute("filtroStatus");
        String cTitulo = (String) session.getAttribute("titulo");
        String cEmpresa = (String) session.getAttribute("empresa");

        if (cTitulo == null) {
            cTitulo = "RELATÓRIO FINANCEIRO";
        }

        Object cWhereClassificacao = session.getAttribute("filtroRelatorioClassificao");
        Object cAssuntoClassificacao = session.getAttribute("filtroAssuntoClassificao");
        Usuario usuario = (Usuario) session.getAttribute("usuarioAutenticado");

        Map parametros = new HashMap();

        if (cWhere == null) {
            cWhere = " ";
        }
        if (cOrder == null) {
            cOrder = " ";
        } else {
            if (cOrder.equals("S")) {
                cOrder = " order by nom_fantasia asc ";
            }
        }
        String caminho = "/WEB-INF/relatorios/";
        String relatorio = "";
        String cSituacao = "";

        String cTipRel = request.getParameter("tipRel");
        String tipStatus = request.getParameter("tipStatus_input");
        String tipSituacao = request.getParameter("tipSituacao_input");
        String tipOrder = request.getParameter("tipOrder_input");

        if (cTipRel == null) {
            cTipRel = (String) session.getAttribute("tipRel");
        }

        if (tipStatus == null) {
            tipStatus = "T";
        }
        if (tipSituacao == null) {
            tipSituacao = "T";
        }
        if (tipOrder == null) {
            tipOrder = "F";
        }

        switch (cTipRel) {
            case "processo":
                relatorio = caminho.concat("relatorio_processo.jasper");
                if (!tipStatus.equals("T")) {
                    cWhere = "WHERE empreendimento_lote.\"status\" = '".concat(tipStatus).concat("' ");
                }
                if (!tipSituacao.equals("T")) {
                    switch (tipSituacao) {
                        case "D":
                            cSituacao = "DEFERIDO";
                            break;
                        case "I":
                            cSituacao = "INDEFERIDO";
                            break;
                        case "A":
                            cSituacao = "EM ANALISE";
                            break;
                    }
                    if (cWhere.contains("WHERE")) {
                        cWhere += " AND processo_situacao.\"ass_situacao\" = '".concat(cSituacao).concat("' ");
                    } else {
                        cWhere = " WHERE processo_situacao.\"ass_situacao\" = '".concat(cSituacao).concat("' ");
                    }
                }
                if (cWhere.contains("WHERE")) {
                    cWhere += " AND empreendimento.\"sta_empreendimento\" = 'A' ";
                } else {
                    cWhere = " WHERE empreendimento.\"sta_empreendimento\" = 'A' ";
                }
                switch (tipOrder) {
                    case "R":
                        cOrder = "ORDER BY cliente.\"nom_cliente\" ";
                        break;
                    case "F":
                        cOrder = "ORDER BY cliente.\"nom_fantasia\" ";
                        break;
                    case "E":
                        cOrder = "ORDER BY empreendimento.\"dsc_empreendimento\" ";
                        break;
                }
                break;
            case "acompanhamento":
                if (!cWhere.trim().isEmpty()) {
                    cWhere += " AND id_usuario = ".concat(usuario.getIdUsuario().toString()).concat(" ");
                } else {
                    cWhere = " WHERE id_usuario = ".concat(usuario.getIdUsuario().toString()).concat(" ");
                }
                relatorio = caminho.concat("relatorio_acompanhamento_processo.jasper");
                break;
            case "classificacao":
                cWhere = " ";
                Cliente[] cWhereClassificacao1 = (Cliente[]) cWhereClassificacao;
                if (cWhereClassificacao1.length > 0) {
                    cWhere = " WHERE cliente.\"id_cliente\" in (";

                    for (Cliente selectedCliente : cWhereClassificacao1) {
                        cWhere += selectedCliente.getIdCliente() + ",";
                    }
                    cWhere += "0) ";
                }
                Assunto[] cAssuntoClassificacao1 = (Assunto[]) cAssuntoClassificacao;
                if (cAssuntoClassificacao1.length > 0) {
                    if (cWhere.toLowerCase().contains("where")) {
                        cWhere += " AND empreendimento_lote.\"id_assunto\" in (";
                    } else {
                        cWhere = " WHERE empreendimento_lote.\"id_assunto\" in (";
                    }

                    for (Assunto selectedAssunto : cAssuntoClassificacao1) {
                        cWhere += selectedAssunto.getIdAssunto() + ",";
                    }
                    cWhere += "0) ";
                }
                if (!cStatus.equals("T")) {
                    if (cWhere.toLowerCase().contains("where")) {
                        cWhere += " AND empreendimento_lote.\"status\" = '".concat(cStatus).concat("' ");
                    } else {
                        cWhere += " WHERE empreendimento_lote.\"status\" = '".concat(cStatus).concat("' ");
                    }
                }
                cOrder = " ORDER BY cliente.\"nom_cliente\" ASC, empreendimento.\"dsc_empreendimento\" ASC ";
                session.removeAttribute("filtroRelatorioClassificao");
                session.removeAttribute("filtroAssuntoClassificao");
                session.removeAttribute("filtroStatus");
                relatorio = caminho.concat("relatorio_classificacao_processo.jasper");
                break;
            case "pagarreceber":
                cWhere = "";
                cOrder = "";
                parametros.put("PAR_EMPRESA", cEmpresa);
                parametros.put("PAR_TITULO", cTitulo);
                parametros.put("PAR_USUARIO", usuario.getIdUsuario());
                relatorio = caminho.concat("relatorio_financeiro.jasper");
                break;
        }

        //String arquivo = context.getRealPath(relatorio);
        String dirsub = context.getRealPath(caminho);

        Conecta conecta = new Conecta();

        JRAbstractLRUVirtualizer virtualizer = new JRGzipVirtualizer(100);

        InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream(relatorio);

        try {
            if (!cWhere.isEmpty()) {
                parametros.put("PAR_WHERE", cWhere);
            }
            if (!cOrder.isEmpty()) {
                parametros.put("PAR_ORDER", cOrder);
            }

            String rootDir = context.getContextPath().concat("/logo/patricia_triunfo.png");
            parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            parametros.put("SUBREPORT_DIR", dirsub.concat(File.separator));
            parametros.put("LOGO", dirsub.concat("\\patricia_triunfo.png"));
            parametros.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));

            //para gerar o relatório em PDF
            // o método runReportToPdfStream foi usado
            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parametros, conecta.Conecta());

            // envia o relatório em formato PDF para o browser
            response.setContentType("application/pdf");

        } catch (SQLException ex) {
            //Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (JRException e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        } finally {
            servletOutputStream.flush();
            servletOutputStream.close();
            reportStream.close();
            session.removeAttribute("filtroRelatorio");
            session.removeAttribute("filtroOrder");
            session.removeAttribute("filtroStatus");
            session.removeAttribute("titulo");
            try {
                conecta.close();
            } catch (SQLException ex) {
                //Logger.getLogger(ReportUtil.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        /*
         ServletOutputStream servletOutputStream = response.getOutputStream();
         ServletContext context = getServletContext();
         session = request.getSession(false);
         String cWhere = (String) session.getAttribute("filtroRelatorio");
         String cOrder = (String) session.getAttribute("filtroOrder");

         Map parametros = new HashMap();

         if (cWhere == null) {
         cWhere = " ";
         }
         if (cOrder == null) {
         cOrder = " ";
         } else {
         if (cOrder.equals("S")) {
         cOrder = " order by nom_fantasia asc ";
         }
         }
        
         parametros = request.getParameterMap();
        
         String caminho = "/WEB-INF/relatorios/";
         String relatorio = "";
         String cSituacao = "";

         String cTipRel = request.getParameter("tipRel");
         String tipStatus = request.getParameter("tipStatus_input");
         String tipSituacao = request.getParameter("tipSituacao_input");
         String tipOrder = request.getParameter("tipOrder_input");

         if (tipStatus == null) {
         tipStatus = "T";
         }
         if (tipSituacao == null) {
         tipSituacao = "T";
         }
         if (tipOrder == null) {
         tipOrder = "F";
         }

         if (cTipRel.equals("processo")) {
         relatorio = caminho.concat("relatorio_processo.jasper");

         if (!tipStatus.equals("T")) {
         cWhere = "WHERE empreendimento_lote.\"status\" = '".concat(tipStatus).concat("' ");
         }
         if (!tipSituacao.equals("T")) {
         if (tipSituacao.equals("D")) {
         cSituacao = "DEFERIDO";
         } else if (tipSituacao.equals("I")) {
         cSituacao = "INDEFERIDO";
         } else if (tipSituacao.equals("A")) {
         cSituacao = "EM ANALISE";
         }
         if (cWhere.contains("WHERE")) {
         cWhere += " AND processo_situacao.\"ass_situacao\" = '".concat(cSituacao).concat("' ");
         } else {
         cWhere = " WHERE processo_situacao.\"ass_situacao\" = '".concat(cSituacao).concat("' ");
         }
         }

         if (cWhere.contains("WHERE")) {
         cWhere += " AND empreendimento.\"sta_empreendimento\" = 'A' ";
         } else {
         cWhere = " WHERE empreendimento.\"sta_empreendimento\" = 'A' ";
         }

         if (tipOrder.equals("R")) {
         cOrder = "ORDER BY cliente.\"nom_cliente\" ";
         } else if (tipOrder.equals("F")) {
         cOrder = "ORDER BY cliente.\"nom_fantasia\" ";
         } else if (tipOrder.equals("E")) {
         cOrder = "ORDER BY empreendimento.\"dsc_empreendimento\" ";
         }
         } else if (cTipRel.equals("acompanhamento")) {
         relatorio = caminho.concat("relatorio_acompanhamento_processo.jasper");
         //cWhere = " WHERE dsc_lote not like '%DEMOLIÇÃO%' and dsc_lote not like '%STAND%' ";
         }

         //String arquivo = context.getRealPath(relatorio);
         String dirsub = context.getRealPath(caminho);

         Conecta conecta = new Conecta();

         JRAbstractLRUVirtualizer virtualizer = new JRGzipVirtualizer(100);

         InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream(relatorio);

         try {
         if (!cWhere.isEmpty()) {
         parametros.put("PAR_WHERE", cWhere);
         }
         if (!cOrder.isEmpty()) {
         parametros.put("PAR_ORDER", cOrder);
         }
         String rootDir = context.getContextPath().concat("/logo/patricia_triunfo.png");
         parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
         parametros.put("SUBREPORT_DIR", dirsub.concat(File.separator));
         parametros.put("LOGO", dirsub.concat("\\patricia_triunfo.png"));

         //para gerar o relatório em PDF
         // o método runReportToPdfStream foi usado
         JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parametros, conecta.Conecta());

         // envia o relatório em formato PDF para o browser
         response.setContentType("application/pdf");

         } catch (SQLException ex) {
         //Logger.getLogger("global").log(Level.SEVERE, null, ex);
         } catch (JRException e) {
         StringWriter stringWriter = new StringWriter();
         PrintWriter printWriter = new PrintWriter(stringWriter);
         e.printStackTrace(printWriter);
         response.setContentType("text/plain");
         response.getOutputStream().print(stringWriter.toString());
         } finally {
         servletOutputStream.flush();
         servletOutputStream.close();
         reportStream.close();
         try {
         conecta.close();
         } catch (SQLException ex) {
         //Logger.getLogger(ReportUtil.class.getName()).log(Level.SEVERE, null, ex);
         }

         }
         */
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
